package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.MessageRedisConstant;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysEnterprise;
import com.ruoyi.system.domain.SysPosition;
import com.ruoyi.system.service.ISysEnterpriseService;
import com.ruoyi.system.service.ISysPositionService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysDialogueMapper;
import com.ruoyi.system.domain.SysDialogue;
import com.ruoyi.system.service.ISysDialogueService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 对话Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-09
 */
@Service
public class SysDialogueServiceImpl extends ServiceImpl<SysDialogueMapper,SysDialogue> implements ISysDialogueService
{
    @Autowired
    private SysDialogueMapper sysDialogueMapper;

    @Autowired
    private ISysPositionService positionService ;

    @Autowired
    private ISysEnterpriseService enterpriseService ;

    @Autowired
    private ISysUserService userService ;

    @Autowired
    private RedisCache redisCache ;

    /**
     * 查询对话
     * 
     * @param id 对话主键
     * @return 对话
     */
    @Override
    public SysDialogue selectSysDialogueById(Long id)
    {
        SysDialogue dialogue = sysDialogueMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(dialogue.getPositionId())) {
            SysPosition position = positionService.getById(dialogue.getPositionId());
            dialogue.setPosition(position);
            SysEnterprise enterprise = enterpriseService.getById(position.getEnterpriseId());
            dialogue.setEnterprise(enterprise);
        }
        return dialogue;
    }

    /**
     * 查询对话列表
     * 
     * @param sysDialogue 对话
     * @return 对话
     */
    @Override
    public List<SysDialogue> selectSysDialogueList(SysDialogue sysDialogue)
    {
        List<SysDialogue> list = sysDialogueMapper.selectSysDialogueList(sysDialogue);
        for (SysDialogue dialogue : list) {
            if (ObjectUtils.isNotEmpty(dialogue.getPositionId())) {
                SysPosition position = positionService.getById(dialogue.getPositionId());
                dialogue.setPosition(position);
                SysEnterprise enterprise = enterpriseService.getById(position.getEnterpriseId());
                dialogue.setEnterprise(enterprise);
            }
            Long userId = SecurityUtils.getUserId();
            String key = MessageRedisConstant.CURRENT_USER_CONTENT_UN_READ_MESSAGE_NUMBER + userId + MessageRedisConstant.UNDERLINE + dialogue.getId();
            Integer currentDialogueUnReadNumber = redisCache.getCacheObject(key);
            dialogue.setUnReadNumber(currentDialogueUnReadNumber);
        }
        Long dialogueId = 0L ;
        if (ObjectUtils.isEmpty(sysDialogue.getId())) {
            Optional<SysDialogue> first = list.stream().findFirst();
            first.ifPresent(dialogue -> dialogue.setOpenContent(1));
            dialogueId = first.get().getId() ;
        }else {
            list.stream().filter(d->d.getId().equals(sysDialogue.getId())).findFirst().ifPresent(d->d.setOpenContent(1));
            LambdaUpdateWrapper<SysDialogue> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(SysDialogue::getId ,sysDialogue.getId()) ;
            wrapper.set(SysDialogue::getUpdateTime ,new Date()) ;
            this.update(wrapper) ;
            dialogueId = sysDialogue.getId() ;
        }

        /**清除未读消息数量*/
        Integer allUnReadNumber = redisCache.getCacheObject(MessageRedisConstant.CURRENT_USER_UN_READ_MESSAGE_NUMBER + SecurityUtils.getUserId());
        if (ObjectUtils.isNotEmpty(allUnReadNumber)) {
            Integer currentDialogueUnReadNumber = redisCache.getCacheObject(MessageRedisConstant.CURRENT_USER_CONTENT_UN_READ_MESSAGE_NUMBER + SecurityUtils.getUserId() + MessageRedisConstant.UNDERLINE + dialogueId);
            if (ObjectUtils.isNotEmpty(currentDialogueUnReadNumber)) {
                redisCache.setCacheObject(MessageRedisConstant.CURRENT_USER_UN_READ_MESSAGE_NUMBER + SecurityUtils.getUserId() ,allUnReadNumber - currentDialogueUnReadNumber);
                redisCache.setCacheObject(MessageRedisConstant.CURRENT_USER_CONTENT_UN_READ_MESSAGE_NUMBER + SecurityUtils.getUserId() + MessageRedisConstant.UNDERLINE + dialogueId ,0) ;
            }
        }

        return list;
    }

    /**
     * 新增对话
     * 
     * @param sysDialogue 对话
     * @return 结果
     */
    @Override
    public int insertSysDialogue(SysDialogue sysDialogue)
    {
        Long userId = SecurityUtils.getUserId();
        sysDialogue.setCreateTime(DateUtils.getNowDate());
        sysDialogue.setOwnerId(userId);
        if (ObjectUtils.isEmpty(sysDialogue.getPositionId())) {
            throw new ServiceException("岗位信息不能为空!") ;
        }
        SysPosition position = positionService.getById(sysDialogue.getPositionId());
        SysEnterprise enterprise = enterpriseService.getById(position.getEnterpriseId());
        sysDialogue.setEnterpriseName(enterprise.getName());
        sysDialogue.setPositionName(position.getName());
        sysDialogue.setUserId(enterprise.getUserId());
        sysDialogue.setUpdateTime(new Date());
        sysDialogue.setCreateTime(new Date());
        SysUser sysUser = userService.selectUserById(sysDialogue.getEnterprise().getUserId());
        sysDialogue.setUserName(sysUser.getNickName());
        int insert = sysDialogueMapper.insert(sysDialogue);
        return insert;
    }

    /**
     * 修改对话
     * 
     * @param sysDialogue 对话
     * @return 结果
     */
    @Override
    public int updateSysDialogue(SysDialogue sysDialogue)
    {
        sysDialogue.setUpdateTime(DateUtils.getNowDate());
        return sysDialogueMapper.updateById(sysDialogue);
    }

    /**
     * 批量删除对话
     * 
     * @param ids 需要删除的对话主键
     * @return 结果
     */
    @Override
    public int deleteSysDialogueByIds(Long[] ids)
    {
        return sysDialogueMapper.deleteSysDialogueByIds(ids);
    }

    /**
     * 删除对话信息
     * 
     * @param id 对话主键
     * @return 结果
     */
    @Override
    public int deleteSysDialogueById(Long id)
    {
        return sysDialogueMapper.deleteSysDialogueById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysDialogue> jumpToContent(SysDialogue sysDialogue) {
        /**首页进入  学生进入*/
        LambdaQueryWrapper<SysDialogue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDialogue::getOwnerId,SecurityUtils.getUserId());
        wrapper.eq(SysDialogue::getPositionId ,sysDialogue.getPositionId()) ;
        SysDialogue one = this.getOne(wrapper);
        if (ObjectUtils.isEmpty(one)) {
            sysDialogue.setOwnerId(SecurityUtils.getUserId());
            sysDialogue.setUserId(sysDialogue.getEnterprise().getUserId());
            SysPosition position = positionService.getById(sysDialogue.getPositionId());
            sysDialogue.setPositionName(position.getName());
            sysDialogue.setEnterpriseName(sysDialogue.getEnterprise().getName());
            SysUser sysUser = userService.selectUserById(sysDialogue.getEnterprise().getUserId());
            sysDialogue.setUserName(sysUser.getNickName());
            sysDialogue.setUpdateTime(new Date());
            sysDialogue.setCreateTime(new Date());
            sysDialogue.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            this.save(sysDialogue);
        }
        LambdaUpdateWrapper<SysDialogue> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SysDialogue::getUpdateTime ,new Date());
        updateWrapper.eq(SysDialogue::getId ,sysDialogue.getId()) ;
        this.update(updateWrapper) ;
        LambdaQueryWrapper<SysDialogue> objectLambdaQueryWrapper = new LambdaQueryWrapper<SysDialogue>();
        objectLambdaQueryWrapper.eq(SysDialogue::getOwnerId ,SecurityUtils.getUserId()) ;
        objectLambdaQueryWrapper.orderByDesc(SysDialogue::getUpdateTime) ;
        List<SysDialogue> list = this.list(objectLambdaQueryWrapper);
        /**对话页面进入*/
        if (ObjectUtils.isEmpty(one)) {
            sysDialogue.setId(sysDialogue.getId());
        }else {
            sysDialogue.setId(one.getId());
        }
        list.stream().filter(d->d.getId().equals(sysDialogue.getId())).findFirst().get().setOpenContent(1) ;
        for (SysDialogue dialogue : list) {
            if (ObjectUtils.isNotEmpty(dialogue.getPositionId())) {
                SysPosition position = positionService.getById(dialogue.getPositionId());
                dialogue.setPosition(position);
                SysEnterprise enterprise = enterpriseService.getById(position.getEnterpriseId());
                dialogue.setEnterprise(enterprise);
            }
            Integer currentDialogueUnReadNumber = redisCache.getCacheObject(MessageRedisConstant.CURRENT_USER_CONTENT_UN_READ_MESSAGE_NUMBER + SecurityUtils.getUserId() + MessageRedisConstant.UNDERLINE + sysDialogue.getId());
            dialogue.setUnReadNumber(currentDialogueUnReadNumber);
        }

        /**清除未读消息数量*/
        Integer allUnReadNumber = redisCache.getCacheObject(MessageRedisConstant.CURRENT_USER_UN_READ_MESSAGE_NUMBER + SecurityUtils.getUserId());
        if (ObjectUtils.isNotEmpty(allUnReadNumber)) {
            Integer currentDialogueUnReadNumber = redisCache.getCacheObject(MessageRedisConstant.CURRENT_USER_CONTENT_UN_READ_MESSAGE_NUMBER + SecurityUtils.getUserId() + MessageRedisConstant.UNDERLINE + sysDialogue.getId());
            if (ObjectUtils.isNotEmpty(currentDialogueUnReadNumber)) {
                redisCache.setCacheObject(MessageRedisConstant.CURRENT_USER_UN_READ_MESSAGE_NUMBER + SecurityUtils.getUserId() ,allUnReadNumber - currentDialogueUnReadNumber);
                redisCache.setCacheObject(MessageRedisConstant.CURRENT_USER_CONTENT_UN_READ_MESSAGE_NUMBER + SecurityUtils.getUserId() + MessageRedisConstant.UNDERLINE + sysDialogue.getId() ,0) ;
            }
        }
        return list;
    }
}
